package com.zrx.govern.component.easyexcel.starter.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.zrx.govern.component.easyexcel.starter.entity.ExcelExportProcess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxiaowei
 * @desc easyexcel自定义写入拦截器，用于计算进度
 */
@Slf4j
public class CustomRowWriteHandler implements RowWriteHandler {

    /**
     * 控制计算进度的速率
     */
    private static final Integer CACHE_COUNT = 20;

    private ExcelExportProcess excelExportProcess;

    private BigDecimal total;

    private BigDecimal hundredBigDecimal;

    private RedisTemplate redisTemplate;

    public CustomRowWriteHandler(ExcelExportProcess excelExportProcess, RedisTemplate redisTemplate) {
        this.excelExportProcess = excelExportProcess;
        this.redisTemplate = redisTemplate;
        total = new BigDecimal(excelExportProcess.getTotal());
        hundredBigDecimal = new BigDecimal(100);
    }

    @Override
    public void afterRowCreate(RowWriteHandlerContext context) {
        int curr = excelExportProcess.increment();
        if (curr % CACHE_COUNT == 0 || curr == excelExportProcess.getTotal()) {
            redisTemplate.opsForValue().set(excelExportProcess.getExportRedisKey(), calRadio(curr),5, TimeUnit.SECONDS);
        }
    }

    /**
     * 计算占比
     *
     * @param cur   分子
     * @return 百分比
     */
    private String calRadio(int cur) {
        //计算插入的数据和总数据的占比
        return new BigDecimal(cur).divide(total, 2, BigDecimal.ROUND_HALF_UP).multiply(hundredBigDecimal).toString();
    }

}
